package com.whpost.service.dao.t;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.entity.t.TMenu;
import com.whpost.service.entity.t.TXzjg;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

public interface TXzjgDao extends BaseMapper<TXzjg> {

    @Select("select * from t_xzjg where ${ew.sqlSegment}")
    @Results(id="tXzjgMap",value = {
            @Result(column="pid",property="pXzjg",
                    one=@One(
                            select="com.whpost.service.dao.t.TXzjgDao.selectById")
            ),
            @Result(column="pid",property="pid")
    })
    List<TXzjg> getTXzjgList(@Param("ew") QueryWrapper wrapper);

    //自己和下级
    @Select("SELECT * FROM t_xzjg START WITH id = #{id} CONNECT BY PRIOR id = pid")
    @ResultMap(value="tXzjgMap")
    List<TXzjg> getXzjgXj(Long id);

    //查询下级，不包含自己
    @Select("SELECT * from t_xzjg where id!=#{id} CONNECT BY PRIOR id = pid START WITH id = #{id}")
    @ResultMap(value="tXzjgMap")
    List<TXzjg> getXzjgXjNoRoot(Long id);

    @Select("SELECT * from t_xzjg where id=#{id}")
    @ResultMap(value="tXzjgMap")
    TXzjg getXzjgById(String id);

    //树形查询
    @Select("SELECT LPAD(' ', (LEVEL - 1) * 4) || id AS indented_id, id, pid, jb, LEVEL AS tree_level, SYS_CONNECT_BY_PATH(name, ' > ') AS full_name, CONNECT_BY_ISLEAF AS is_leaf FROM t_xzjg START WITH id = #{id} CONNECT BY NOCYCLE PRIOR id = pid ORDER SIBLINGS BY id")
    List<Map<String,String>> getXzjgTree(Long id);

    //获取所有行政机构的id
    @Select("SELECT id FROM t_xzjg START WITH id = #{id} CONNECT BY NOCYCLE PRIOR id = pid ORDER SIBLINGS BY id")
    List<Long> getAllId(Long id);

    //更新级别
    @Update("UPDATE t_xzjg SET jb = (SELECT parent.jb + 1 FROM t_xzjg parent WHERE parent.id = #{id}) WHERE id IN (SELECT id FROM t_xzjg START WITH id = #{id} CONNECT BY PRIOR id = pid MINUS SELECT #{id} FROM dual)")
    int updateJb(Long id);

    @Update("update t_xzjg set pid=null,jb=1 where id=#{id}")
    int setPidNull(Long id);
}